<template>
  <view class="mian">
	<view id="captureArea"  class="flex flex-direction">		
		<view class="class_h" style="background-color: #fff">
			<view class="top" @click="return_step">					
				<image src="../../../static/resource/back.png" mode="aspectFill" style="width: 74px;height: 30px;"></image>				
			</view>
			<text class="task_name">订单管理</text>
		</view>		
		<view class="content_one">
			<view class="flex pt-50 pl-30 pr-30">
				<view class="flex flex-direction justify-between">
					<view class="containersss">
						<view class="member-bg"  :style="{ backgroundImage: `url(${userInfo.token ? userInfo.member_level : 'https://tangmaibao.site/static/upload/f42b5b566c89345e/e83497a25fc61e7d.png'})`}"></view>
						<image class="mine__bg--avatar" mode="aspectFill" style="background:" v-if="!userInfo.token" src="/static/mine/avatar.png" @click="userInfo.token?setBase():$routers.routeToLogin(recommendId)"></image>
						<image class="mine__bg--avatar" mode="aspectFill" style="background:" v-if="userInfo.token" :src="userInfo.wx_icon?userInfo.wx_icon:'/static/mine/avatar.png'" @click="setBase()"></image>	
					</view>					
				</view>
				<view class="flex flex-direction" style="margin-left: 30px;">
					<text class="text-bold">{{userInfo.nickName}}</text>
					<view class="flex flex-direction mt-20" style="color: #666666;">
						<view class="flex" style="gap: 18px;">
							<text class="mt-10">性別：{{userInfo.gender}}</text>
							<text class="mt-10">身高：{{userInfo.heights}}</text>
						</view>
						<view class="flex mt-10" style="gap: 18px;">
							<text class="mt-10">年龄：{{userInfo.age}}</text>
							<text class="mt-10">体重：{{userInfo.weights}}</text>
						</view>
					</view>					
				</view>
			</view>
			
			<view class="flex justify-center align-center pt-50 mb-20">
				<image src="../../../static/order/Line59.png" style="height: 1px;"></image>
			</view>
					
			<view class="flex justify-start align-center text-center pl-30 pt-20">
				<view class="flex">
					<image src="../../../static/resource/sugar_icon.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
				</view>
				<text class="effect_t ml-15">血糖（mmol/L）</text>
			</view>	
			
			<view class="flex flex-wrap  pt-30 pl-30 pr-30 ">
				<view class="flex health" v-for="(item,index) in userInfo.blood_measure_sugar " :key="index">
					<text class="h_name">{{item.sugar_value}}</text>
					<text class="h_name">血糖中位数</text>
					<view class="flex align-center justify-center text-center pt-20 pb-30">
						<text class="flex">{{item.blood_sugar}}</text>
						<text class="effect_t">mmol/L</text>
					</view>
				</view>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">分层占比</text>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-40">
				<canvas
				  canvas-id="bloodChart"
				  id="bloodChart"
				  class="chart"
				></canvas>
				
				<view class="legend ml-50">
				  <view class="legend-item">
					<view class="dot" style="background:#F56202"></view> 偏高
				  </view>
				  <view class="legend-item">
					<view class="dot" style="background:#FDC24E"></view> 偏低
				  </view>
				  <view class="legend-item">
					<view class="dot" style="background:#1EC157"></view> 正常
				  </view>
				</view>
				
				
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">达标率</text>
			</view>
			
			<view class="flex pt-20 pl-20 pr-30 align-center text-center ">			
				<view class="progress-wrap">
					<view class="progress-bg">
					
					  <view
						class="progress-bar"
						:style="{ width: userInfo.bloodSugarData_report_rate + '%' }"
						>
						<text class="progress-text">{{ userInfo.bloodSugarData_report_rate }}%</text>
					  </view>
					</view>
				</view>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">健康建议</text>
			</view>
			<view class="mt-20 ml-20 mr-20  p-20 mb-30"  style="border-radius: 8px; font-size: 28rpx;line-height: 44rpx; color: #666666;background-color: #ECF0F6;">
				
				<text >近一周血糖 存在波动，但整体呈下降趋势，请注意保持健康生活方式！</text>
			</view>
		
		</view>
		
		<view class="content_two">
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
					<image src="../../../static/resource/pressure_icon.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
				</view>
				<text class="effect_t ml-15">血压（mmhg）</text>
			</view>
			
			<view class="flex flex-wrap  pt-30 pl-30 ">
				<view class="flex healths" v-for="(item,index) in userInfo.blood_measure_pressure " :key="index">
					<text class="h_name">{{item.sugar_value}}</text>
					<text class="h_name">血压中位数</text>
					<view class="flex align-center justify-center text-center pt-20 pb-10">
						<text class="flex">舒张压:{{item.blood_dbp}}</text>
						<text class="effect_t ml-15">mmHg</text>
					</view>
					<view class="flex align-center justify-center text-center  pb-30 pl-10">
						<text class="flex">收缩压:{{item.blood_sbp}}</text>
						<text class="effect_t ml-15">mmHg</text>
					</view>
				</view>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">分层占比</text>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-40 flex-direction ">
				<view class="flex">
					<canvas
					  canvas-id="bloodChartPressure"
					  id="bloodChartPressure"
					  class="chart"
					></canvas>
					<canvas
					  canvas-id="bloodChartPressureSbp"
					  id="bloodChartPressureSbp"
					  class="chart"
					></canvas>
					
				</view>
			
				
				<view class="legend ml-50" style="flex-direction:row">
				  <view class="legend-item">
					<view class="dot" style="background:#F56202"></view> 偏高
				  </view>
				  <view class="legend-item">
					<view class="dot" style="background:#FDC24E"></view> 偏低
				  </view>
				  <view class="legend-item">
					<view class="dot" style="background:#1EC157"></view> 正常
				  </view>
				</view>
				
				
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">达标率（舒张压）</text>
			</view>

			<view class="flex pt-20 pl-20 pr-30 align-center text-center ">			
				<view class="progress-wrap">
					<view class="progress-bg">
					
					  <view
						class="progress-bar"
						:style="{ width: userInfo.dbp_range_report_rate + '%' }"
					  >
						<text class="progress-text">{{ userInfo.dbp_range_report_rate }}%</text>
					  </view>
					</view>
				</view>
			</view>
			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">达标率（压缩压）</text>
			</view>
			
			<view class="flex pt-20 pl-20 pr-30 align-center text-center ">			
				<view class="progress-wrap">
					<view class="progress-bg">
					
					  <view
						class="progress-bar"
						:style="{ width: userInfo.sbp_range_report_rate + '%' }"
					  >
						<text class="progress-text">{{ userInfo.sbp_range_report_rate }}%</text>
					  </view>
					</view>
				</view>
			</view>

			
			<view class="flex justify-start align-center text-center pl-30 mt-30">
				<view class="flex">
				  <image src="/static/resource/measure.png" mode="aspectFill" style="width: 3px;height: 10px;"></image>
				</view>
				<text class="effect_t ml-15">健康建议</text>
			</view>
			<view class="mt-20 ml-20 mr-20  p-20 mb-30"  style="border-radius: 8px; font-size: 28rpx;line-height: 44rpx; color: #666666;background-color: #ECF0F6;">
				
				<text >近一周 血压 存在波动，但整体呈下降趋势，请注意保持健康生活方式！</text>
			</view>
			
		</view>
		
		
	</view>
<!-- 	<view class="flex pb-30 flex-direction" style="width: 93%;margin-left: 32rpx;margin-right: 40rpx;">
		<button formType="submit" style="background: #FFC116; color: white; width: 100%;margin-right: 40rpx; margin-top: 20rpx;"   @click="share_sign()">分享</button>
	</view>
    <canvas canvas-id="shareCanvas" style="width: 750rpx; height: 1334rpx; position: absolute; left:-9999px;" /> -->
	
	
  </view>
</template>

<script>
import pop from "@/components/pop/pop";
import TimeCurveChart  from '@/components/dui-line-chart/TimeCurveChart.vue'

export default {
		components: {
		   "regional-selection": pop,
					TimeCurveChart
		 },	
	data() {
		return {	
			...getApp().globalData.config,
			progress:10,
			chartData: [
			   { time: "08:00", value: 90 },
			   { time: "10:00", value: 100 },
			   { time: "12:00", value: 80 },
			   { time: "14:00", value: 110 },
			   { time: "16:00", value: 95 }
			],
			userInfo:{},
			// 血糖分层数据
			bloodSugarData_report: [],		
			// 血压舒张压
			dbp_range_report: [],
			// 血压收缩压
			sbp_range_report:[]
	    }
	},
   onShow() {	
	  // this.userInfo=uni.getStorageSync('userInfo');	
	  this.query_report()
	  
	
   },	
   onReady() {
   

   },
   methods: {	  
	   
	...getApp().globalData.function, 
	
share_sign() {
  uni.showLoading({ title: '生成中...' });

  // 必须用微信原生 query
  const query = wx.createSelectorQuery().in(this);
  query.select('#captureArea').fields({ node: true, size: true }).exec(async res => {
    const element = res[0];
    if (!element || !element.node) {
      uni.hideLoading();
      return uni.showToast({ title: '未找到截图区域', icon: 'none' });
    }

    const canvas = element.node;
    const width = element.width;
    const height = element.height;

    canvas.width = width * 2;   // 放大以保证清晰
    canvas.height = height * 2;
    const ctx = canvas.getContext('2d');
    ctx.scale(2, 2);

    try {
      await canvas.draw();  // 把节点绘制到canvas

      wx.canvasToTempFilePath({
        canvas,
        width,
        height,
        destWidth: width * 2,
        destHeight: height * 2,
        success: res2 => {
          wx.saveImageToPhotosAlbum({
            filePath: res2.tempFilePath,
            success: () => {
              uni.hideLoading();
              uni.showToast({ title: '已保存到相册', icon: 'success' });
            },
            fail: err => {
              uni.hideLoading();
              uni.showToast({ title: '保存失败', icon: 'none' });
              console.error(err);
            }
          });
        },
        fail: err => {
          uni.hideLoading();
          uni.showToast({ title: '生成失败', icon: 'none' });
          console.error(err);
        }
      });
    } catch (e) {
      uni.hideLoading();
      uni.showToast({ title: '生成失败', icon: 'none' });
      console.error(e);
    }
  });
},

	
	query_report(){
		let that =this
		let obj={
			token:uni.getStorageSync('userInfo').token
		}
	  this.$http.userReport(obj).then(res=>{
		 if(res.resCode=='9999'){
			 this.userInfo=res.data
			 this.bloodSugarData_report=res.data.bloodSugarData_report
			 this.dbp_range_report=res.data.dbp_range_report
			 this.sbp_range_report=res.data.sbp_range_report
			 
			 // 数据加载 & DOM 渲染完成后再画图
		   this.$nextTick(() => {
			 setTimeout(() => {
			   that.drawBloodChart();
			   that.drawBloodChartPressure();
			   that.bloodChartPressureSbps()
			 }, 300);
		   });
				   
				   
		 }
	  })	
	},
	
	return_step(){
	  	this.$routers.router('/pages/mine/index','switchTab') 
	},
	  
    drawBloodChart() {
      const ctx = uni.createCanvasContext('bloodChart', this)
     const width = 160
           const height = 160
           const cx = width / 2
           const cy = height / 2
           const outerRadius = 60
           const innerRadius = 45


      // 八个时间点及状态
       const bloodData = this.bloodSugarData_report  // ← 使用 data 里的

      // 颜色对应
      const colorMap = {
        偏高: '#F56202',
        偏低: '#FDC24E',
        正常: '#1EC157',
      }

      const segmentAngle = (2 * Math.PI) / bloodData.length
      let startAngle = -Math.PI / 2

      // 绘制8段环
      bloodData.forEach((item, index) => {
        const endAngle = startAngle + segmentAngle
        ctx.beginPath()
        ctx.arc(cx, cy, outerRadius, startAngle, endAngle)
        ctx.arc(cx, cy, innerRadius, endAngle, startAngle, true)
        ctx.closePath()
        ctx.setFillStyle(colorMap[item.status])
        ctx.fill()
        startAngle = endAngle
      })

      // 中心文字
      ctx.setFontSize(18)
      ctx.setFillStyle('#333')
      ctx.setTextAlign('center')
      ctx.fillText('血糖', cx, cy - 5)
      ctx.setFontSize(14)
      ctx.setFillStyle('#888')
      ctx.fillText('概况', cx, cy + 20)

      // 外部时间点文字
      bloodData.forEach((item, i) => {
        const angle = (-Math.PI / 2) + i * segmentAngle + segmentAngle / 2
        const textRadius = outerRadius + 20
        const tx = cx + Math.cos(angle) * textRadius
        const ty = cy + Math.sin(angle) * textRadius

        ctx.setFontSize(12)
        ctx.setFillStyle('#333')
        ctx.setTextAlign('center')
        ctx.setTextBaseline('middle')
        ctx.fillText(item.time, tx, ty)
      })

      ctx.draw()
    },
	drawBloodChartPressure() {
	  const ctx = uni.createCanvasContext('bloodChartPressure', this)
	 const width = 160
	       const height = 160
	       const cx = width / 2
	       const cy = height / 2
	       const outerRadius = 60
	       const innerRadius = 45
	
	
	  // 八个时间点及状态
	  const bloodData = this.dbp_range_report // 使用 data 中的
	
	  // 颜色对应
	  const colorMap = {
	    偏高: '#F56202',
	    偏低: '#FDC24E',
	    正常: '#1EC157',
	  }
	
	  const segmentAngle = (2 * Math.PI) / bloodData.length
	  let startAngle = -Math.PI / 2
	
	  // 绘制8段环
	  bloodData.forEach((item, index) => {
	    const endAngle = startAngle + segmentAngle
	    ctx.beginPath()
	    ctx.arc(cx, cy, outerRadius, startAngle, endAngle)
	    ctx.arc(cx, cy, innerRadius, endAngle, startAngle, true)
	    ctx.closePath()
	    ctx.setFillStyle(colorMap[item.status])
	    ctx.fill()
	    startAngle = endAngle
	  })
	
	  // 中心文字
	  ctx.setFontSize(18)
	  ctx.setFillStyle('#333')
	  ctx.setTextAlign('center')
	  ctx.fillText('血压', cx, cy - 5)
	  ctx.setFontSize(14)
	  ctx.setFillStyle('#888')
	  ctx.fillText('舒张压', cx, cy + 20)
	
	  // 外部时间点文字
	  bloodData.forEach((item, i) => {
	    const angle = (-Math.PI / 2) + i * segmentAngle + segmentAngle / 2
	    const textRadius = outerRadius + 20
	    const tx = cx + Math.cos(angle) * textRadius
	    const ty = cy + Math.sin(angle) * textRadius
	
	    ctx.setFontSize(12)
	    ctx.setFillStyle('#333')
	    ctx.setTextAlign('center')
	    ctx.setTextBaseline('middle')
	    ctx.fillText(item.time, tx, ty)
	  })
	
	  ctx.draw()
	},
    bloodChartPressureSbps(){
		const ctx = uni.createCanvasContext('bloodChartPressureSbp', this)
		const width = 160
		      const height = 160
		      const cx = width / 2
		      const cy = height / 2
		      const outerRadius = 60
		      const innerRadius = 45
			
			
		 // 八个时间点及状态
		 const bloodData = this.sbp_range_report // 使用 data 中的
			
		 // 颜色对应
		 const colorMap = {
		   偏高: '#F56202',
		   偏低: '#FDC24E',
		   正常: '#1EC157',
		 }
			
		 const segmentAngle = (2 * Math.PI) / bloodData.length
		 let startAngle = -Math.PI / 2
			
		 // 绘制8段环
		 bloodData.forEach((item, index) => {
		   const endAngle = startAngle + segmentAngle
		   ctx.beginPath()
		   ctx.arc(cx, cy, outerRadius, startAngle, endAngle)
		   ctx.arc(cx, cy, innerRadius, endAngle, startAngle, true)
		   ctx.closePath()
		   ctx.setFillStyle(colorMap[item.status])
		   ctx.fill()
		   startAngle = endAngle
		 })
			
		 // 中心文字
		 ctx.setFontSize(18)
		 ctx.setFillStyle('#333')
		 ctx.setTextAlign('center')
		 ctx.fillText('血压', cx, cy - 5)
		 ctx.setFontSize(14)
		 ctx.setFillStyle('#888')
		 ctx.fillText('收缩压', cx, cy + 20)
			
		 // 外部时间点文字
		 bloodData.forEach((item, i) => {
		   const angle = (-Math.PI / 2) + i * segmentAngle + segmentAngle / 2
		   const textRadius = outerRadius + 20
		   const tx = cx + Math.cos(angle) * textRadius
		   const ty = cy + Math.sin(angle) * textRadius
			
		   ctx.setFontSize(12)
		   ctx.setFillStyle('#333')
		   ctx.setTextAlign('center')
		   ctx.setTextBaseline('middle')
		   ctx.fillText(item.time, tx, ty)
		 })
			
		 ctx.draw()
	}
  },
}
</script>

<style scoped>
 @import "./index.css";
</style>
